import {createAsyncThunk} from "@reduxjs/toolkit";
import {Project} from "@/schemas/project.ts";
import {ListQuery} from "@/schemas/invoke.ts";
import {invokeListQuery, invokeOperationOne} from "@/communicate/rust-invoke.ts";
import {queryFive} from "@/common/default-some.ts";


const fetchProject = async (query: ListQuery, rejectWithValue:any) => {
    const resp = await invokeListQuery<Project>(
        'project/all', 'ListQuery', query
    )
    if (resp.ok) return resp.data?.result || []
    return rejectWithValue('获取项目列表失败！')
}

export const ListProject = createAsyncThunk(
    "project/list",
    async (query: ListQuery, {rejectWithValue}) => await fetchProject(query,rejectWithValue)
)


export const CreateProject = createAsyncThunk(
    "project/create",
    async (data: Project, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'project/create', 'CreateProject', data
        )
        if (resp.ok) return await fetchProject(queryFive, rejectWithValue)
        return rejectWithValue("创建项目失败！")
    }
)

export const ImportProject = createAsyncThunk(
    "project/import",
    async (data: Project, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'project/import', 'CreateProject', data
        )
        if (resp.ok) return await fetchProject(queryFive, rejectWithValue)
        return rejectWithValue("导入项目失败！")
    }
)


export const LoadProject = createAsyncThunk(
    "project/load",
    async (item: Project, {rejectWithValue}) => {
        const resp = await invokeOperationOne('project/load', 'OperateProject', {id: item.id})
        if (resp.ok) return item
        return rejectWithValue('加载失败！')
    }
)